<?php
/**
 * 命令解释器
 * 
 * @version $Id: ICommandInterpreter.php 312 2008-04-23 16:29:38Z iwind $
 * @package net.4kiki.cli
 */
class ICommandInterpreter extends IObject {
	/**
	 * 运行一个命令
	 *
	 * @param IAbstractCommand $command 命令类
	 */
	public static function executeCommand(IAbstractCommand $command) {
		$arguments = $_SERVER["argv"];
		$command->initOptions();
		$parameters = $command->getParameterMap();
		$lastParameter = null;
		if (!empty($arguments)) {
			foreach ($arguments as $argument) {
				if (self::isOption($argument)) {
					$element = self::getElement($parameters, $argument);
					if ($element != null) {
						$element["option"]->setDefined(true);
						$lastParameter = $element["parameter"];
					}
				}
				else {
					if (strstr($argument, "=") != "") {
						list($_option, $_value) = explode("=", $argument, 2);
						if (self::isOption($_option)) {
							$element = self::getElement($parameters, $_option);
							if ($element != null) {
								$element["option"]->setDefined(true);
								$lastParameter = $element["parameter"];
								$lastParameter->setValue($_value);
							}
						}
						else if ($lastParameter != null) {
							$lastParameter->setValue($argument);
							$lastParameter = null;
						}
					}
					else if ($lastParameter != null) {
						$lastParameter->setValue($argument);
						$lastParameter = null;
					}
				}
			}
		}
		
		
		$command->execute();
	}
	
	/**
	 * 取得一个选项对应的参数对象及选项对象
	 *
	 * @param unknown_type $parameters
	 * @param unknown_type $optionName
	 * @return array
	 */
	private static function getElement($parameters, $optionName) {
		if (!empty($parameters)) {
			foreach ($parameters as $parameter) {
				foreach ($parameter->getOptions() as $option) {
					if ($option->getName() == $optionName) {
						return array("parameter" => $parameter, "option"=>$option);
					}
				}
			}
		}
		return null;
	}
	
	private static function isOption($argument) {
		return (preg_match("/^\\-+[a-z0-9]+$/i", trim($argument)))?true:false;
	}
}

?>